package cn.jx.asc.mqtt.handle;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.jx.asc.common.constant.netconst;
import cn.jx.asc.common.utils.MD5Utils;
import cn.jx.asc.common.utils.StringUtils;
import cn.jx.asc.common.utils.conversUtil;
import cn.jx.asc.dao.mapper.*;
import cn.jx.asc.parseupload.OkHttpUtil2;
import cn.jx.asc.parseupload.model.onenetdata;
import cn.jx.asc.pojo.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

import static cn.jx.asc.common.constant.netconst.NO;
import static cn.jx.asc.common.constant.netconst.WARING_THRESHOLD;

/**
 * @author z423
 * @2021-06-13-19:40
 * @effect
 * @especial
 */

@Slf4j
@Component
public class MessageArrivedHandler implements MessageHandler {
    @Autowired
    private MountainMapper mountainMapper;
    @Autowired
    private PipeStatusMapper pipeStatusMapper;
    @Autowired
    private PipeMapper pipeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private ThresholdMapper thresholdMapper;

    @Override
    public void handle(Long msgId, String msgBody) {
        OkHttpUtil2 okHttpUtil2 = new OkHttpUtil2();
        onenetdata data = parseData(msgBody);
        if (null != data) {
            //log.info("数据解析成功: {}", data);
            switch (data.getCtrl()) {
                //如果为公有数据上传命令
                case netconst.CTRL_TYPE_ONE:
                    Integer[] integer = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    //插入环境温湿度
                    Date createTime = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    final String ctime = dateFormat.format(createTime);
                    Timestamp d1 = new Timestamp(System.currentTimeMillis());

                    Mountain mountain = new Mountain(UUID.randomUUID().toString(),integer[5], integer[1], integer[0], integer[4], integer[3], integer[2],integer[8],d1);

                    mountainMapper.insert(mountain);
                    //改变矿井当前控制状态
                    Timestamp d2 = new Timestamp(System.currentTimeMillis());
                    PipeStatus pipeStatus = new PipeStatus(integer[5], integer[6], d2);
                    QueryWrapper<PipeStatus> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("pipe_Id", integer[5]);
                    pipeStatusMapper.update(pipeStatus, wrapper1);
                    //修改插入矿井数据
                    Timestamp d3 = new Timestamp(System.currentTimeMillis());
                    Pipe pipe = new Pipe(UUID.randomUUID().toString(),integer[5], integer[5], integer[9], integer[8], integer[7], integer[10], d3);
                    pipeMapper.insert(pipe);
                    break;
                //用户密码修改上传
                case netconst.CTRL_TYPE_TWO:
                    User user = null;
                    try {
                        user = new User("user", MD5Utils.getMD5Str(data.getValue()[0]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    QueryWrapper<User> wrapper = new QueryWrapper<>();
                    wrapper.eq("username", "user");
                    int update = userMapper.update(user, wrapper);
                    //告知对方服务器是否收到修改
                    if (update != 0) {
                        okHttpUtil2.issue("A，2，1");
                    } else {
                        okHttpUtil2.issue("A，2，0");
                    }
                    break;
                //修改液面阈值
                case netconst.CTRL_TYPE_THREE:
                    Integer[] binteger = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    Threshold threshold = new Threshold(binteger[0], data.getValue()[1], data.getValue()[2], data.getValue()[3], data.getValue()[4]);
                    int i = thresholdMapper.updateById(threshold);
                    if (i != 0) {
                        okHttpUtil2.issue("A,4,1");
                    } else {
                        okHttpUtil2.issue("A,4,0");
                    }
                    break;
                case netconst.CTRL_TYPE_FOUR:
                    Integer[] cinteger = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    netconst.CONFIR_WARING=cinteger[0];
                    break;
                case netconst.CTRL_TYPE_FIVE:
                    Integer[] dinteger = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    WARING_THRESHOLD=dinteger[0];
                    break;
                case netconst.CTRL_TYPE_SIX:
                    Integer[] einteger = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    netconst.HEIGHT_THRESHOLD=einteger[0];
                    break;
                case netconst.CTRL_TYPE_SEVEN:
                    Integer[] finteger = conversUtil.getInteger(conversUtil.getDouble(data.getValue()));
                    netconst.CONSELE=finteger[0];
                    break;
                default:
                    //错误命令
                    log.warn("非法的命令");
            }
        }
    }

    /**
     * 将数据解析为onenetdata类
     *
     * @param content 即有用数据body
     * @return onenetdata类
     */
    private onenetdata parseData(String content) {
        JSONObject object = JSONUtil.parseObj(content);
        String body = object.getStr("body");
        String[] arr = body.trim().split(",");
       // log.info("OneNet 接收到数据: {}", body);
        if (arr.length == netconst.DATA_LENGTH) {
            //数据头
            String head = arr[0];
            //功能码
            String ctrl = arr[1];
            //具体数据值,将数据串放在数组里分别解析
            String[] value = new String[11];
            for (int i = 2; i <= 12; i++) {
                value[i - 2] = arr[i];
            }
            log.info("数据帧头："+head+" "+"功能码："+ctrl+"  "+"数据值："+ Arrays.toString(value));
            return onenetdata.builder()
                    .head(head)
                    .ctrl(ctrl)
                    .value(value)
                    .build();
        } else {
            //log.warn("获取OneNet数据长度与数据定义格式长度不符");
            return null;
        }
    }
}

